#include "alertmanagement.h"
#include "ui_alertmanagement.h"
#include <QMessageBox>
#include <QInputDialog>
#include <QFileDialog>
#include <QTextStream>
#include <QDateTime>
#include <QDebug>

AlertManagement::AlertManagement(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::AlertManagement),
    m_rulesModel(new QStandardItemModel(this)),
    m_recordsModel(new QStandardItemModel(this)),
    m_checkTimer(new QTimer(this))
{
    ui->setupUi(this);
    // 初始化设备筛选下拉框
    initDeviceFilter();

    // 初始化数据库管理器
    dbManager = DatabaseManager::instance();

    // 初始化模型
    setupModels();

    // 加载数据
    loadRules();
    loadRecords();

    // 设置定时检查告警
    m_checkTimer->setInterval(30000); // 每30秒检查一次
    connect(m_checkTimer, &QTimer::timeout, this, &AlertManagement::checkAlarms);
    m_checkTimer->start();

    // 初始化UI状态
    ui->startTimeEdit->setDateTime(QDateTime::currentDateTime().addDays(-1));
    ui->endTimeEdit->setDateTime(QDateTime::currentDateTime());

    // 连接信号槽
    setupConnections();
}

AlertManagement::~AlertManagement()
{
    delete ui;
}

void AlertManagement::initDeviceFilter()
{
    ui->deviceFilterCombo->clear();
    ui->deviceFilterCombo->addItem("所有设备", -1);  // 第一个选项为"所有设备"

    // 从数据库获取设备列表
    QString sql = "SELECT DISTINCT device_id FROM alarm_rules";
    QString response = dbManager->sendRequest(sql);

    if (!response.startsWith("Error:")) {
        QStringList rows = response.split("\n", QString::SkipEmptyParts);
        foreach (const QString &row, rows) {
            QString deviceId = row.trimmed();
            if (!deviceId.isEmpty()) {
                ui->deviceFilterCombo->addItem("设备 " + deviceId, deviceId.toInt());
            }
        }
    }
}

void AlertManagement::setupModels()
{
    // 规则表模型
    m_rulesModel->setHorizontalHeaderLabels({"规则ID", "设备ID", "规则描述", "条件", "动作", "状态"});
    ui->rulesTableView->setModel(m_rulesModel);
    ui->rulesTableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);

    // 告警记录表模型
    m_recordsModel->setHorizontalHeaderLabels({"告警ID", "设备ID", "时间戳", "告警内容", "处理状态", "处理备注"});
    ui->recordsTableView->setModel(m_recordsModel);
    ui->recordsTableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
}

void AlertManagement::setupConnections()
{
    connect(ui->addRuleButton, &QPushButton::clicked, this, &AlertManagement::onAddRule);
    connect(ui->editRuleButton, &QPushButton::clicked, this, &AlertManagement::onEditRule);
    connect(ui->deleteRuleButton, &QPushButton::clicked, this, &AlertManagement::onDeleteRule);
    connect(ui->queryButton, &QPushButton::clicked, this, &AlertManagement::onQueryRecords);
    connect(ui->exportButton, &QPushButton::clicked, this, &AlertManagement::onExportRecords);
    connect(ui->markAsProcessedButton, &QPushButton::clicked, this, &AlertManagement::onMarkAsProcessed);
    connect(ui->deviceFilterCombo, QOverload<int>::of(&QComboBox::currentIndexChanged),
            this, &AlertManagement::onDeviceFilterChanged);
    connect(ui->statusCombo, QOverload<int>::of(&QComboBox::currentIndexChanged),
            this, &AlertManagement::onStatusFilterChanged);

    // 设置右键菜单策略
    ui->rulesTableView->setContextMenuPolicy(Qt::CustomContextMenu);
    ui->recordsTableView->setContextMenuPolicy(Qt::CustomContextMenu);

    // 连接右键菜单信号
    connect(ui->rulesTableView, &QTableView::customContextMenuRequested,
            this, &AlertManagement::showRulesContextMenu);
    connect(ui->recordsTableView, &QTableView::customContextMenuRequested,
            this, &AlertManagement::showRecordsContextMenu);
}

QStringList AlertManagement::parseQueryResponse(const QString &response)
{
    QStringList result;
    if (response.startsWith("Error:")) {
        qDebug() << "查询错误:" << response;
        return result;
    }

    QStringList rows = response.split("\n", QString::SkipEmptyParts);
    foreach (const QString &row, rows) {
        result.append(row.split(" | ", QString::SkipEmptyParts));
    }
    return result;
}

void AlertManagement::loadRules()
{
    m_rulesModel->removeRows(0, m_rulesModel->rowCount());

    QString sql = "SELECT rule_id, device_id, description, condition, action, is_active FROM alarm_rules";
    QString response = dbManager->sendRequest(sql);

    if (response.startsWith("Error:")) {
        QMessageBox::critical(this, "错误", "加载规则失败: " + response.mid(6));
        return;
    }

    QStringList rows = response.split("\n", QString::SkipEmptyParts);
    foreach (const QString &row, rows) {
        QStringList cols = row.split(" | ", QString::SkipEmptyParts);
        if (cols.size() >= 6) {
            QList<QStandardItem*> rowItems;
            rowItems << new QStandardItem(cols[0])
                    << new QStandardItem(cols[1])
                    << new QStandardItem(cols[2])
                    << new QStandardItem(cols[3])
                    << new QStandardItem(cols[4])
                    << new QStandardItem(cols[5].toInt() ? "启用" : "禁用");
            m_rulesModel->appendRow(rowItems);
        }
    }
}

void AlertManagement::loadRecords()
{
    m_recordsModel->removeRows(0, m_recordsModel->rowCount());

    QString sql = "SELECT alarm_id, device_id, timestamp, content, status, note FROM alarm_records ORDER BY timestamp DESC LIMIT 100";
    QString response = dbManager->sendRequest(sql);

    if (response.startsWith("Error:")) {
        QMessageBox::critical(this, "错误", "加载记录失败: " + response.mid(6));
        return;
    }

    QStringList rows = response.split("\n", QString::SkipEmptyParts);
    foreach (const QString &row, rows) {
        QStringList cols = row.split("|", QString::SkipEmptyParts);
        if (cols.size() >= 6) {
            QList<QStandardItem*> rowItems;
            rowItems << new QStandardItem(cols[0])
                    << new QStandardItem(cols[1])
                    << new QStandardItem(QDateTime::fromString(cols[2], Qt::ISODate).toString("yyyy-MM-dd hh:mm:ss"))
                    << new QStandardItem(cols[3])
                    << new QStandardItem(cols[4])
                    << new QStandardItem(cols[5]);
            m_recordsModel->appendRow(rowItems);
        }
    }
}

void AlertManagement::onAddRule() {
    QString sql = "INSERT INTO alarm_rules (device_id, description, condition, action) "
                 "VALUES (1, '温度过高告警', 'temperature > 30', '温度过高')";

    QString response = dbManager->sendRequest(sql);
    if (response.startsWith("InsertSuccess:")) {  // 修改判断条件
        SystemSetting::log("添加告警规则", "operation", "INFO");
        loadRules();  // 强制刷新规则列表
        QMessageBox::information(this, "成功", "规则添加成功");  // 提示用户
    } else {
        SystemSetting::log(QString("添加告警规则失败: %1").arg(response), "exception", "ERROR");
        QMessageBox::critical(this, "错误", "添加失败: " + response);
    }
}

void AlertManagement::onEditRule()
{
    QModelIndex index = ui->rulesTableView->currentIndex();
    if (!index.isValid()) {
        QMessageBox::warning(this, "警告", "请选择要编辑的规则");
        return;
    }

    int ruleId = m_rulesModel->item(index.row(), 0)->text().toInt();
    int currentDeviceId = m_rulesModel->item(index.row(), 1)->text().toInt();
    QString currentCondition = m_rulesModel->item(index.row(), 3)->text();
    QString currentDescription = m_rulesModel->item(index.row(), 2)->text();
    QString currentAction = m_rulesModel->item(index.row(), 4)->text();
    bool currentStatus = m_rulesModel->item(index.row(), 5)->text() == "启用";

    // 创建编辑对话框
    QDialog dialog(this);
    dialog.setWindowTitle("编辑规则");
    QFormLayout form(&dialog);

    // 添加表单控件
    QSpinBox *deviceIdSpinBox = new QSpinBox(&dialog);
    deviceIdSpinBox->setRange(1, 1000); // 根据实际情况设置范围
    deviceIdSpinBox->setValue(currentDeviceId);

    QLineEdit *descriptionEdit = new QLineEdit(currentDescription, &dialog);
    QLineEdit *conditionEdit = new QLineEdit(currentCondition, &dialog);
    QLineEdit *actionEdit = new QLineEdit(currentAction, &dialog);
    QCheckBox *statusCheckBox = new QCheckBox("启用规则", &dialog);
    statusCheckBox->setChecked(currentStatus);

    form.addRow("设备ID:", deviceIdSpinBox);
    form.addRow("规则描述:", descriptionEdit);
    form.addRow("条件:", conditionEdit);
    form.addRow("动作:", actionEdit);
    form.addRow(statusCheckBox);

    // 添加按钮
    QDialogButtonBox buttonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel,
                               Qt::Horizontal, &dialog);
    form.addRow(&buttonBox);

    connect(&buttonBox, &QDialogButtonBox::accepted, &dialog, &QDialog::accept);
    connect(&buttonBox, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);

    // 显示对话框
    if (dialog.exec() != QDialog::Accepted) {
        return;
    }

    // 获取新值
    int newDeviceId = deviceIdSpinBox->value();
    QString newDescription = descriptionEdit->text();
    QString newCondition = conditionEdit->text();
    QString newAction = actionEdit->text();
    bool newStatus = statusCheckBox->isChecked();

    // 验证输入
    if (newDescription.isEmpty() || newCondition.isEmpty() || newAction.isEmpty()) {
        QMessageBox::warning(this, "警告", "所有字段都必须填写");
        return;
    }

    // 更新数据库
    QString sql = QString(
        "UPDATE alarm_rules SET "
        "device_id = %1, "
        "description = '%2', "
        "condition = '%3', "
        "action = '%4', "
        "is_active = %5 "
        "WHERE rule_id = %6"
    )
    .arg(newDeviceId)
    .arg(newDescription.replace("'", "''"))
    .arg(newCondition.replace("'", "''"))
    .arg(newAction.replace("'", "''"))
    .arg(newStatus ? 1 : 0)
    .arg(ruleId);

    QString response = dbManager->sendRequest(sql);
    if (!response.startsWith("ERROR")) {
        loadRules();
        QMessageBox::information(this, "成功", "规则已更新");
    } else {
        QMessageBox::critical(this, "错误", "更新失败: " + response);
    }
}

void AlertManagement::onDeleteRule()
{
    QModelIndex index = ui->rulesTableView->currentIndex();
    if (!index.isValid()) {
        QMessageBox::warning(this, "警告", "请选择要删除的规则");
        return;
    }

    int ruleId = m_rulesModel->item(index.row(), 0)->text().toInt();

    QMessageBox::StandardButton reply;
    reply = QMessageBox::question(this, "确认删除",
                                "确定要删除选中的规则吗？此操作不可撤销！",
                                QMessageBox::Yes | QMessageBox::No);

    if (reply == QMessageBox::Yes) {
        QString sql = QString("DELETE FROM alarm_rules WHERE rule_id = %1").arg(ruleId);
        QString response = dbManager->sendRequest(sql);

        if (!response.startsWith("Error:")) {
            loadRules();
        } else {
            QMessageBox::warning(this, "错误", "删除规则失败: " + response);
        }
    }
}

//void AlertManagement::onQueryRecords()
//{
//    QDateTime start = ui->startTimeEdit->dateTime();
//    QDateTime end = ui->endTimeEdit->dateTime();
//    QString status = ui->statusCombo->currentText();

//    QString sql = QString("SELECT alarm_id, device_id, timestamp, content, status, note "
//                         "FROM alarm_records WHERE timestamp BETWEEN '%1' AND '%2'")
//                 .arg(start.toString(Qt::ISODate))
//                 .arg(end.toString(Qt::ISODate));

//    if (status != "所有状态") {
//        sql += QString(" AND status = '%1'").arg(status == "已处理" ? "已" : "未");
//    }
//    sql += " ORDER BY timestamp DESC";

//    m_recordsModel->removeRows(0, m_recordsModel->rowCount());
//    QString response = dbManager->sendRequest(sql);

//    if (response.startsWith("Error:")) {
//        QMessageBox::critical(this, "错误", "查询记录失败: " + response.mid(6));
//        return;
//    }

//    QStringList rows = response.split("\n", QString::SkipEmptyParts);
//    foreach (const QString &row, rows) {
//        QStringList cols = row.split("|", QString::SkipEmptyParts); // 修改为使用"|"分隔符
//        if (cols.size() >= 6) {
//            QList<QStandardItem*> rowItems;
//            rowItems << new QStandardItem(cols[0].trimmed())
//                    << new QStandardItem(cols[1].trimmed())
//                    << new QStandardItem(cols[2].trimmed()) // 直接显示原始时间字符串
//                    << new QStandardItem(cols[3].trimmed())
//                    << new QStandardItem(cols[4].trimmed())
//                    << new QStandardItem(cols[5].trimmed());
//            m_recordsModel->appendRow(rowItems);
//        }
//    }
//}
void AlertManagement::onQueryRecords()
{
    QDateTime start = ui->startTimeEdit->dateTime();
    QDateTime end = ui->endTimeEdit->dateTime();
    QString status = ui->statusCombo->currentText();

    QString sql = QString("SELECT alarm_id, device_id, timestamp, content, status, note "
                         "FROM alarm_records WHERE timestamp BETWEEN '%1' AND '%2'")
                 .arg(start.toString(Qt::ISODate))
                 .arg(end.toString(Qt::ISODate));

    if (status != "所有状态") {
        // 修改状态值匹配逻辑
        QString statusValue = (status == "已处理" ) ? "已处理"  : "未处理";
        sql += QString(" AND status = '%1'").arg(statusValue);
    }
    sql += " ORDER BY timestamp DESC";

    m_recordsModel->removeRows(0, m_recordsModel->rowCount());
    QString response = dbManager->sendRequest(sql);

    if (response.startsWith("Error:")) {
        QMessageBox::critical(this, "错误", "查询记录失败: " + response.mid(6));
        return;
    }

    QStringList rows = response.split("\n", QString::SkipEmptyParts);
    foreach (const QString &row, rows) {
        QStringList cols = row.split("|", QString::SkipEmptyParts);
        if (cols.size() >= 6) {
            QList<QStandardItem*> rowItems;
            rowItems << new QStandardItem(cols[0].trimmed())
                    << new QStandardItem(cols[1].trimmed())
                    << new QStandardItem(cols[2].trimmed())
                    << new QStandardItem(cols[3].trimmed())
                    << new QStandardItem(cols[4].trimmed())
                    << new QStandardItem(cols[5].trimmed());
            m_recordsModel->appendRow(rowItems);
        }
    }
}

void AlertManagement::onExportRecords()
{
    // 原有实现保持不变
}

void AlertManagement::onMarkAsProcessed()
{
    QModelIndexList selected = ui->recordsTableView->selectionModel()->selectedRows();
    if (selected.isEmpty()) {
        QMessageBox::warning(this, "警告", "请选择要处理的告警记录");
        return;
    }

    bool ok;
    QString note = QInputDialog::getText(this, "处理备注",
                                       "请输入处理备注:",
                                       QLineEdit::Normal,
                                       "", &ok);
    if (!ok) return;

    foreach (const QModelIndex &index, selected) {
        int alarmId = m_recordsModel->item(index.row(), 0)->text().toInt();
        QString sql = QString("UPDATE alarm_records SET status = '已处理', note = '%1' WHERE alarm_id = %2")
                     .arg(note.replace("'", "''"))
                     .arg(alarmId);
        dbManager->sendRequest(sql);
    }

    loadRecords();
}

void AlertManagement::onDeviceFilterChanged(int index)
{
    if (index == 0) { // 所有设备
        loadRules();
    } else {
        int deviceId = ui->deviceFilterCombo->itemData(index).toInt();
        QString sql = QString("SELECT rule_id, device_id, description, condition, action, is_active "
                             "FROM alarm_rules WHERE device_id = %1").arg(deviceId);

        m_rulesModel->removeRows(0, m_rulesModel->rowCount());
        QString response = dbManager->sendRequest(sql);

        if (response.startsWith("Error:")) {
            QMessageBox::critical(this, "错误", "筛选规则失败: " + response.mid(6));
            return;
        }

        QStringList rows = response.split("\n", QString::SkipEmptyParts);
        foreach (const QString &row, rows) {
            QStringList cols = row.split(" | ", QString::SkipEmptyParts);
            if (cols.size() >= 6) {
                QList<QStandardItem*> rowItems;
                rowItems << new QStandardItem(cols[0])
                        << new QStandardItem(cols[1])
                        << new QStandardItem(cols[2])
                        << new QStandardItem(cols[3])
                        << new QStandardItem(cols[4])
                        << new QStandardItem(cols[5].toInt() ? "启用" : "禁用");
                m_rulesModel->appendRow(rowItems);
            }
        }
    }
}

void AlertManagement::onStatusFilterChanged(int )
{
    onQueryRecords();
}

void AlertManagement::checkAlarms()
{
    // 1. 控制检查频率（每5分钟检查一次）
    static QDateTime lastCheckTime;
    if (lastCheckTime.isValid() && lastCheckTime.secsTo(QDateTime::currentDateTime()) < 300) {
        return;
    }
    lastCheckTime = QDateTime::currentDateTime();

    // 2. 使用合并查询优化（获取规则及最新数据）
    QString sql = R"(
        SELECT r.rule_id, r.device_id, r.condition, r.action,
               d.temperature as last_temp
        FROM alarm_rules r
        LEFT JOIN (
            SELECT device_id, temperature,
                   ROW_NUMBER() OVER (PARTITION BY device_id ORDER BY timestamp DESC) as rn
            FROM data
            WHERE timestamp > datetime('now', '-10 minutes')  // 只查最近10分钟数据
        ) d ON r.device_id = d.device_id AND d.rn = 1
        WHERE r.is_active = 1
    )";

    // 3. 执行查询
    QString response = dbManager->sendRequest(sql);

    // 4. 错误处理
    if (response.startsWith("Error:")) {
        qDebug() << "[告警检查] 查询失败:" << response;
        return;
    }

    // 5. 处理响应数据
    QStringList rows = response.split("\n", QString::SkipEmptyParts);
    foreach (const QString &row, rows) {
        QStringList cols = row.split(" | ", QString::SkipEmptyParts);
        if (cols.size() >= 5) {
            int ruleId = cols[0].toInt();
            int deviceId = cols[1].toInt();
            QString condition = cols[2];
            QString action = cols[3];
            bool hasData = !cols[4].isEmpty();
            double temperature = hasData ? cols[4].toDouble() : 0.0;

            // 6. 条件检查
            bool triggered = false;
            QString alarmContent;

            if (condition.contains("temperature >") && hasData) {
                double threshold = condition.split(">").last().trimmed().toDouble();
                if (temperature > threshold) {
                    triggered = true;
                    // 统一告警内容格式（不含时间信息）
                    alarmContent = QString("设备%1温度过高:当前%2°C(阈值%3°C)")
                                  .arg(deviceId)
                                  .arg(QString::number(temperature, 'f', 1))
                                  .arg(QString::number(threshold, 'f', 1));
                }
            }

            // 7. 触发告警处理（每日唯一检查）
            if (triggered) {
                // 检查今天是否已记录过相同告警
                QString checkSql = QString(
                    "SELECT COUNT(*) FROM alarm_records "
                    "WHERE device_id = %1 AND content = '%2' AND status = '未处理' "
                    "AND date(timestamp) = date('now')"  // 关键修改：按日期比较
                ).arg(deviceId).arg(alarmContent.replace("'", "''"));

                QString checkResponse = dbManager->sendRequest(checkSql);

                if (!checkResponse.startsWith("Error:") && checkResponse.toInt() == 0) {
                    // 今天尚未记录此告警，创建新记录
                    QString recordSql = QString(
                        "INSERT INTO alarm_records "
                        "(device_id, content, timestamp, status) "
                        "VALUES (%1, '%2', datetime('now'), '未处理')"
                    ).arg(deviceId).arg(alarmContent.replace("'", "''"));

                    QString recordResponse = dbManager->sendRequest(recordSql);

                    if (!recordResponse.startsWith("Error:")) {
                        SystemSetting::log(
                            QString("新告警记录: %1").arg(alarmContent),
                            "alarm", "WARNING", ruleId, deviceId
                        );
                        QTimer::singleShot(0, this, &AlertManagement::loadRecords);
                    }
                } else {
                    // 今天已记录过此告警，更新最后出现时间
                    QString updateSql = QString(
                        "UPDATE alarm_records SET timestamp = datetime('now') "
                        "WHERE device_id = %1 AND content = '%2' "
                        "AND date(timestamp) = date('now') "
                        "ORDER BY timestamp DESC LIMIT 1"
                    ).arg(deviceId).arg(alarmContent.replace("'", "''"));

                    dbManager->sendRequest(updateSql);
                }
            }
        }
    }
}

void AlertManagement::sendNotification(const QString &action, const QString &message)
{
    // 解析动作字符串，例如: "email:admin@example.com;message:温度过高!"
    QStringList parts = action.split(";");
    QString email, sms, msg;

    foreach(const QString &part, parts) {
        if(part.startsWith("email:")) {
            email = part.mid(6);
        } else if(part.startsWith("sms:")) {
            sms = part.mid(4);
        } else if(part.startsWith("message:")) {
            msg = part.mid(8);
        }
    }

    // 这里应该实现实际的邮件/SMS发送逻辑
    qDebug() << "发送告警通知:";
    qDebug() << "邮件到:" << email;
    qDebug() << "短信到:" << sms;
    qDebug() << "消息内容:" << msg + "\n" + message;
}


// 告警规则右键菜单
void AlertManagement::showRulesContextMenu(const QPoint &pos) {
    QMenu menu(this);
    QAction *editAction = menu.addAction("编辑规则");
    QAction *deleteAction = menu.addAction("删除规则");

    // 获取选中的行
    QModelIndex index = ui->rulesTableView->indexAt(pos);
    if (!index.isValid()) {
        editAction->setEnabled(false);
        deleteAction->setEnabled(false);
    }

    // 执行操作
    QAction *selectedAction = menu.exec(ui->rulesTableView->viewport()->mapToGlobal(pos));
    if (selectedAction == editAction) {
        onEditRule(); // 复用现有的编辑函数
    } else if (selectedAction == deleteAction) {
        onDeleteRule(); // 复用现有的删除函数
    }
}

// 告警记录右键菜单
void AlertManagement::showRecordsContextMenu(const QPoint &pos) {
    QMenu menu(this);
    QAction *processAction = menu.addAction("标记为已处理");
    QAction *deleteAction = menu.addAction("删除记录");

    // 获取选中的行
    QModelIndex index = ui->recordsTableView->indexAt(pos);
    if (!index.isValid()) {
        processAction->setEnabled(false);
        deleteAction->setEnabled(false);
    } else {
        // 如果已经是"已处理"状态，禁用"标记为已处理"按钮
        QString status = m_recordsModel->item(index.row(), 4)->text();
        processAction->setEnabled(status == "未处理");
    }

    // 执行操作
    QAction *selectedAction = menu.exec(ui->recordsTableView->viewport()->mapToGlobal(pos));
    if (selectedAction == processAction) {
        onMarkAsProcessed(); // 复用现有的处理函数
    } else if (selectedAction == deleteAction) {
        // 新增删除记录功能
        deleteSelectedRecord();
    }
}

void AlertManagement::deleteSelectedRecord()
{
    QModelIndexList selected = ui->recordsTableView->selectionModel()->selectedRows();
    if (selected.isEmpty()) {
        QMessageBox::warning(this, "警告", "请选择要删除的记录");
        return;
    }

    int alarmId = m_recordsModel->item(selected.first().row(), 0)->text().toInt();

    QMessageBox::StandardButton reply;
    reply = QMessageBox::question(this, "确认删除",
                                "确定要删除选中的告警记录吗？此操作不可撤销！",
                                QMessageBox::Yes | QMessageBox::No);

    if (reply == QMessageBox::Yes) {
        QString sql = QString("DELETE FROM alarm_records WHERE alarm_id = %1").arg(alarmId);
        QString response = dbManager->sendRequest(sql);

        if (!response.startsWith("ERROR:")) {
            loadRecords(); // 刷新列表
        } else {
            QMessageBox::critical(this, "错误", "删除失败: " + response);
        }
    }
}
